import { defineStore } from "pinia";
import { userApi } from "@/api";
import { Storeage } from "@/utils/tools";
import { routes as Routes } from "@/router/routes";
import type { IUserState } from "../typings";
import type { IloginForm, IUser } from "@/api/typings";

export default defineStore('user', {
  state: (): IUserState => ({
    userInfo: Storeage.getItem('USERINFO'),
    menuRoutes: Routes,
    token: Storeage.getItem('TOKEN'),
    menuFold: false
  }),
  actions: {
    async login(data: IloginForm) {
      try {
        const { code, data: respData, message } = await userApi.login(data)
        if (code === 200) {
          this.userInfo = respData || {}
          this.token = (respData as IUser).token
          Storeage.setItem('USERINFO', respData)
          Storeage.setItem('TOKEN', (respData as IUser).token)
          Promise.resolve()
        } else {
          return Promise.reject(new Error(message))
        }
      } catch (error) {
        return Promise.reject(new Error((error as Error).message))
      }
    },
    async userLoginOut() {
      this.userInfo = {}
      this.token = ''
      Storeage.remove('USERINFO')
      Storeage.remove('TOKEN')
      return Promise.resolve('success')
    }
  }
})